import query from './atom/db/query';
import count from './atom/db/count';
import { IBaseTable } from './atom/db/interfaces';

declare const action_id: string;
declare const session_id: string;
declare const spaceid: string;

//参数
interface Message {
	filter: {};
	sort: {};
	page_size: number;
	page_no: number;
}

interface certifiInfo extends IBaseTable {
	_id: string; 			//_id
	no: string; 			//编号
	staff_name: string; 	//员工名称
	staff_number: string; 	//员工编号
	staff_type: string		//员工类型
	deptid: string; 		//部门编号
	deptname: string;		//部门名称
	papers_type: string 	//证件类型
	papers_num: string		//证件号码
	publication_date: number //签发日期
	site: string			//签发地点
	block_date: number 		//有效期至
	accessory_url: string 	//附件
}


function format(date: number) {
	if (date === null) {
		return '';
	}
	try {
		const _date = new Date(parseFloat(date + ''));
		if (_date) {
			return _date.getFullYear() + '-' + _format(_date.getMonth() + 1) + '-' + _format(_date.getDate());
		}
		return '';
	} catch (error) {
		return '';
	}
}

function _format(d: number) {
	if (d < 10) {
		return '0' + d;
	} else {
		return d;
	}
}

async function atom(msg: Message) {
	const systemid = '6051';
	const { exec, prepare } = query(action_id, session_id, spaceid, systemid);
	const asc: string[] = [];
	const desc: string[] = [];
	if (msg.sort) {
		const key = Object.keys(msg.sort)[0];
		if (msg.sort[key] === -1) {
			desc.push(key);
		} else {
			asc.push(key);
		}
	}
	// 证照信息
	prepare('exit_certifi_regist', ['_id', 'no', 'staff_name', 'staff_number', 'staff_type', 'deptid', 'deptname', 'papers_type', 'papers_num', 'publication_date', 'site', 'block_date', 'accessory_url',], msg.filter, msg.page_size, msg.page_no, asc, desc);
	const [data] = await exec();

	data.forEach((item: certifiInfo) => {
		item['publication_date_str'] = format(item.publication_date);
		item['block_date_str'] = format(item.block_date);

	});

	const c = count(action_id, session_id, spaceid, systemid);
	c.prepare('exit_certifi_regist', msg.filter);
	const [t] = await c.exec();

	return { dataArray: data, count: t };
}